//
//  SinaComposePictureController.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/22.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let maxItems = 3

class SinaComposePictureController: UICollectionViewController {

    //装填图片的数组
    lazy var imageArray: [UIImage] = [UIImage]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(SinaComposePictureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }


    

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let delta = imageArray.count == maxItems ? 0 : 1
        
        return imageArray.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SinaComposePictureCell
    
        cell.contentView.backgroundColor = randomColor()
        cell.delegate = self
        //如果是最后一个cell
        if indexPath.item == imageArray.count{
            cell.image = nil
        }else{
            cell.image = imageArray[indexPath.item]
        }
        return cell
    }
}



// MARK:
// MARK: - 遵守发送图片Cell协议的分类
extension SinaComposePictureController: SinaComposePictureCellDelegate{
    
    internal func addBtnClick(sender: UICollectionViewCell?) {
        //modal到图片选择界面
        let pickerVC = UIImagePickerController()
        pickerVC.delegate = self
        pickerVC.view.backgroundColor = UIColor.white
        self.present(pickerVC, animated: true, completion: nil)
    }

    internal func closeBtnClick(sender: UICollectionViewCell) {
        guard let indexPath = collectionView?.indexPath(for: sender) else{
            return
        }
        self.imageArray.remove(at: indexPath.item)
        self.collectionView?.reloadData()
        //若是没有数据了,就把自己隐藏
        self.view.isHidden = self.imageArray.count == 0
    }
}




// MARK:
// MARK: - 遵守picker协议的分类
extension SinaComposePictureController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let pickImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        let smallImage = pickImage.imageWithScaleWidth(width: screenWidth - 2 * margin)
        self.imageArray.append(smallImage)
        picker.dismiss(animated: true, completion: nil)
        self.collectionView?.reloadData()
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
}





// MARK:
// MARK: - 发送图片Cell协议
protocol SinaComposePictureCellDelegate: NSObjectProtocol {
    
    func closeBtnClick(sender: UICollectionViewCell)
    func addBtnClick(sender: UICollectionViewCell?)
    
}



// MARK:
// MARK: - 继承Cell的子类
class SinaComposePictureCell: UICollectionViewCell {
    
    
    
    //懒加载Button
    lazy var addPicBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .highlighted)
        
        return btn
    }()
    
    lazy var closePicBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        
        return btn
    }()
    
    
    //图片
    var image: UIImage?{
        didSet{
            addPicBtn.setImage(image, for: .normal)
            addPicBtn.setImage(image, for: .disabled)
            addPicBtn.isEnabled = image == nil
            closePicBtn.isHidden = image == nil
        }
    }
    
    weak var delegate: SinaComposePictureCellDelegate?
    
    
    
    // MARK:
    // MARK: - 两个按钮触发方法
    @objc private func addBtnDidClick(){
        delegate?.addBtnClick(sender: self)
    }
    @objc private func closeBtnDidClick(){
        delegate?.closeBtnClick(sender: self)
    }
    
    
    
    
    // MARK:
    // MARK: - 重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK:
    // MARK: - 设置界面
    func setupUI() {
        
        self.contentView.addSubview(addPicBtn)
        self.contentView.addSubview(closePicBtn)
        
        addPicBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        closePicBtn.addTarget(self, action: #selector(closeBtnDidClick), for: .touchUpInside)
        
        addPicBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        closePicBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
    }
    
    
}

